﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jbe.TestSuite.Infrastructure.Interface.Documents;
using System.Windows.Documents;
using System.IO;
using System.Windows;
using Jbe.TestSuite.RtfEditor.Properties;

namespace Jbe.TestSuite.RtfEditor.Domain
{
    public class RichTextDocumentType : DocumentType
    {
        public int documentCount;


        public RichTextDocumentType()
            : base(Resources.RichTextDocuments, "rtf")
        {
        }

        public override bool CanNew() { return true; }

        protected override Document NewCore()
        {
            RichTextDocument document = new RichTextDocument(new FlowDocument());
            document.FileName = string.Format(Resources.DocumentTemplate + ".rtf", ++documentCount);
            return document;
        }

        public override bool CanOpen() { return true; }

        protected override Document OpenCore(string fileName)
        {
            FlowDocument flowDocument = new FlowDocument();
            TextRange range = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                range.Load(stream, DataFormats.Rtf);
            }

            RichTextDocument document = new RichTextDocument(flowDocument);
            documentCount++;
            return document;
        }

        public override bool CanSave(Document document) { return document is RichTextDocument; }

        protected override void SaveCore(Document document, string fileName)
        {
            FlowDocument flowDocument = ((RichTextDocument)document).Content;
            TextRange range = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
            using (FileStream stream = new FileStream(fileName, FileMode.Create))
            {
                range.Save(stream, DataFormats.Rtf);
            }
        }
    }
}
